import React,{Component} from 'react';
import { connect } from 'react-redux';
import { Card,Button,Input,Table,message,Select,Modal,Space  } from 'antd';
import { PlusCircleOutlined,ExclamationCircleOutlined,SearchOutlined } from '@ant-design/icons';
import {reqTeacherList,reqAddTeacher,reqUpdateTeacher,reqDeleteTeacher,reqSearchTeacher,reqSearchTeacherInfo} from '../../api';
import { saveTeacherAction } from '../../redux/action_creators/user_action';
import {PAGE_SIZE} from '../../config';
import dayjs from 'dayjs';
const { Option } = Select;

@connect(
    state=>({userList:state.userList}),
    {
        saveTeacherList:saveTeacherAction
    }
)
class Teacher extends Component {
    state={
        userList:[],//用户列表
        roleList:[],//角色列表
        isLoading:true, //table是否显示加载动画
        id:'',
        keyWord:'', //搜索关键词
        searchType:'username',//默认搜索方式按名称搜索
        TeacherCourseList:[],
        isVisible:false
    }
    componentDidMount(){
        const {teacherList } = this.props.userList;
        if(teacherList.length>0){
            // console.log(studentList);
            this.setState({
                userList:teacherList,
                isLoading:false,
            })
        }else{
            this.getTeacherList()
        }
    }

    // 获取用户列表
    getTeacherList = async () => {
        let result = await reqTeacherList()
        const { code,data,msg} = result
        // console.log(result);
       if(code === 200){
            if(data.length===0)  message.success(msg,1)
            this.setState({
                userList:data,
                isLoading:false,
            })
            //   把用户列表保存到redux中
              this.props.saveTeacherList(data)
        }else{
            message.error(msg,1)      
        } 
    }
    // 用户弹窗设置确定
    handleAuthOk = async (values,id,type)=>{
        let result
        // console.log(values,type);
        if(type ==="add"){
            result = await reqAddTeacher(values)
            const { code,data,msg} = result
            if(code === 200){
                message.success('添加用户成功！',1)
                let userList = [...this.state.userList]
                userList.unshift(data)
                this.setState({userList})
                this.props.saveTeacherList(userList)

            }else{
                message.error(msg,1)
            }
        }else{
            result = await reqUpdateTeacher({...values,id})
            // console.log(result);
            const { code,data,msg} = result
            if(code === 200){
                message.success('修改用户成功！',1)
                let userList = [...this.state.userList]
                userList = userList.map((item)=> item.id === data.id ? data : item);
                this.setState({userList})
                this.props.saveTeacherList(userList)
            }else{
                message.error(msg,1)
            }
        }
    }
    // 删除用户信息
    deleteUser =  (id) => {
        let{ getDelete } = this
        Modal.confirm({
            icon: <ExclamationCircleOutlined/>,
            title:'删除用户',
            content:'你确定要删除用户信息吗？',
            okText:'确定',
            cancelText:'取消',
            onOk(){
                getDelete(id)
            },
            onCancel() {
            // console.log('取消');
            },
        });
    }
        // 删除用户信息
        getDelete = async (id) =>{
            let  result = await reqDeleteTeacher(id)
            console.log(id);
            const { code,msg} = result
            if(code === 200){
                message.success('删除用户成功！',1)
                let userList = [...this.state.userList]
                let userIndex;
                userList.forEach((item,index)=> {
                    if(item.id === id) userIndex=index
                });
                userList.splice(userIndex,1)
                this.setState({userList})
                this.props.saveTeacherList(userList)
            }else{
                message.error(msg,1)
            }
        }
    // 根据搜索类型搜索
    searchTeacherType=  () => {
        const {keyWord} = this.state;
        const {teacherList } = this.props.userList;
        if(keyWord.length>0){
            this.searchTeacherList()
        }else{
            this.setState({
                userList:teacherList,
                isLoading:false,
            })
        }
    }
    // 获取讲师信息列表
    searchTeacherList = async () => {
        const {searchType,keyWord} = this.state
        console.log(searchType,keyWord);
        let result = await reqSearchTeacher(searchType,keyWord)
        const { code,data,msg} = result
        console.log(result);
       if(code === 200){
            if(data===null)  message.success(msg,1)
            this.setState({
                userList:data,
                isLoading:false,
            })
              // 把商品列表保存到redux中
            //   this.props.saveProductList(data.list)
        }else{
            message.error(msg,1)      
        } 
    }
     // 展示弹窗
     showModelCourse=async(teacherId)=>{
        console.log(teacherId);
        let result = await reqSearchTeacherInfo('teacherId',teacherId)
        const { code,data,msg} = result
        console.log(result);
       if(code === 200){
        if(data.length===0)  message.success(msg,1)
            this.setState({
                teacherCourseList:data,
                isVisible:true,
            })
        }else{
            message.error(msg,1)      
        } 
    }
    render(){
        const { userList,searchType,teacherCourseList,isVisible } = this.state
        const columns = [
        {title: '姓名',
            dataIndex: 'username',
            key: 'id',
        },
        {title: '工号',
            dataIndex: 'userNum',
            key: 'id',
            },
        {title: '邮箱',
            dataIndex: 'email',
            key: 'id',
        },
        {title: '学位',
            dataIndex: 'degree',
            key: 'id', 
        },
        {title: '职称',
            dataIndex: 'title',
            key: 'id', 
        },
        {title: '电话',
            dataIndex: 'phone',
            key: 'id',
        },
        {title: '操作',
            key: 'id',
            align:'center',
            render:(item)=>{
                return(
                    <div>
                         <Button type="link" onClick={()=>{this.showModelCourse(item.id)}}>个人课程</Button>
                         <Button type="link" onClick={()=>{this.props.history.push(`/training/admin/teacher/detail/${item.id}`)}}>详情</Button>
                         <Button type="link" onClick={()=>{this.props.history.push({ pathname:`/training/admin/teacher/update/${item.id}`,state:{teacherItem:item} })}}>修改</Button>
                         <Button type="link" onClick={()=>{this.deleteUser(item.id)}}>删除</Button>
                    </div>
                )
            }
        },
        ];
        const columnCourse = [
            {
              title: '课程编号',
              dataIndex: 'courseNum',
              key: 'id',
            },
            {
                title: '课程名称',
                dataIndex: 'courseName',
                key: 'id',
            },
            {title: '授课地点',
                dataIndex: 'courseRoom',
                key: 'id', 
            },
            {title: '课程日期',
                dataIndex: 'courseDate',
                key: 'id', 
                render:(courseDate)=>{return courseDate? courseDate.replace(/,/g, " 至 "):''}
            },
            {title: '课程周期',
                dataIndex: 'courseWeek',
                key: 'id',
            
            },
            {title: '课程时间',
                dataIndex: 'courseTime',
                key: 'id',
                render:(courseTime)=>{ return courseTime ? courseTime.replace(/,/g, " 至 ") : ''}
            },
            { title: '创建时间',
                dataIndex: 'createTime',
                key: 'id',
                render:time=>dayjs(time).format('YYYY年MM月DD日  HH:mm:ss')
            },
          ];

        return (
            <div>
                <Card
                    title={
                        <Space size="small">
                        <Select 
                            defaultValue={searchType} 
                            style={{ width: 120 }} 
                            onChange={(value)=>{this.setState({searchType:value})}}
                        >
                            <Option value="username">按姓名搜索</Option>
                            <Option value="userNum">按工号搜索</Option>
                        </Select>
                        <Input 
                         style={{ width: 220 }} 
                            placeholder="请输入关键字" 
                            className="selectInput" 
                            allowClear
                            onChange={(event)=>{this.setState({keyWord:event.target.value})}}
                        />
                        <Button
                            type="primary"
                            onClick={this.searchTeacherType}
                        >
                            <SearchOutlined />搜索
                        </Button>
                         </Space>
                     } 
                     extra={
                        <Button type="primary"  onClick={()=>{this.props.history.push({ pathname:`/training/admin/teacher/update`,state:{teacherItem:[]} })}}>
                        <PlusCircleOutlined/>添加讲师</Button>
                    }
                >
                    <Table 
                        dataSource={userList} 
                        columns={columns}
                        bordered
                        rowKey='id'
                        pagination={{
                            pageSize:PAGE_SIZE,
                        }}
                        loading={this.state.isLoading} 
                    />
                </Card>
                <Modal
                    title="授课课程"
                    visible={isVisible}
                    onOk={()=>this.setState({isVisible:false})}
                    onCancel={()=>this.setState({isVisible:false})}
                    footer={null}
                    maskClosable={false}
                    width={1200}
                    >
                     <Table 
                        dataSource={teacherCourseList} 
                        columns={columnCourse}
                        bordered
                        rowKey='id'
                        pagination={{
                            pageSize:PAGE_SIZE,
                        }}
                        loading={this.state.isLoading} 
                    />
                    </Modal>
            </div>
        );
    }
}
export default Teacher;